package com.dragon.logical.service.auth.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.repository.entity.Version;
import com.dragon.repository.mapper.VersionMapper;
import com.dragon.logical.service.auth.IVersionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 版本信息 服务实现类
 * </p>
 *
 * @author sy
 * @since 2024-01-17
 */
@Service
public class VersionServiceImpl extends ServiceImpl<VersionMapper, Version> implements IVersionService {

    @Autowired
    VersionMapper versionMapper;

    @Override
    public Page<Version> versionList(Integer page, Integer limit) {
        Page<Version> versionPage = new Page<>(page, limit);
        QueryWrapper<Version> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Version::getStatus, 1)
                .orderByDesc(Version::getCreateTime);
        Page<Version> versionPage1 = versionMapper.selectPage(versionPage, wrapper);
        return versionPage1;
    }

    @Override
    public void versionAdd(Version version){
        version.setCreateTime(DateUtil.date());
        versionMapper.insert(version);
    }

    @Override
    public void versionUpdate(Version version){
        Version version1 = versionMapper.selectById(version.getId());
        if (version1 != null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        version.setUpdateTime(DateUtil.date());
        versionMapper.insert(version);
    }

    @Override
    public void versionDelete(Integer id) {
        Version version = versionMapper.selectById(id);
        version.setStatus(2);
        version.setUpdateTime(DateUtil.date());
        versionMapper.updateById(version);
    }

    @Override
    public Version getLatestOne() {
        Version version = versionMapper.selectLatestOne();
        if (version == null){
            return new Version();
        }
        return version;
    }
}
